<?php
namespace lightblog\home\model;

use lightblog\engine\activeRecord;

class articleModel extends activeRecord {

    /**
     * 得到文章列表
     *
     * @param boolean $detail 是不是显示详情
     * @param string $start 开始时间
     * @param string $end 结束时间
     */
    function getArticleList($detail = true, $start = "", $end = "") {
        if ($detail) {
            $more_fields = ", left(`content`, 200)";
        } else {
            $more_fields = "";
        }
        $fields = "`id`, `author`, `title`, `time`, `modified`, `reads`, `thumbsup` $more_fields";
        $sql = "SELECT $fields FROM `article` ORDER BY `modified` DESC";

        return $this->select($sql);
    }

    /**
     * 获取特定的文章
     * @param integer $aid 文章ID
     *
     * @return 相应的内容
     */
    function getArticle($aid = 0) {
        $where = $aid ? "WHERE id = $aid" : "";
        $sql = "SELECT * FROM article $where ORDER BY modified DESC LIMIT 1";

        $article = $this->select($sql, false);
        $article['modified'] = date('M d, Y H:i:s', strtotime($article['modified']));
        $article['time'] = date('M d, Y H:i:s', strtotime($article['time']));
        $article['content'] = htmlspecialchars($article['content']);

        $pn = $this->getPrevNext($article['id']);
        $article['prev'] = $pn['prev'];
        $article['next'] = $pn['next'];

        return $article;
    }

    /**
     * 找到某篇文章的前一篇以及后一篇
     * @param integer $aid 文章的编号
     * @return array 包含前后编号的数组
     */
    function getPrevNext($aid) {
        if ($aid - 1 > 0) {
            $prev_sql = "SELECT id FROM article WHERE id = ($aid - 1)";
            $prev = $this->select($prev_sql, false);
            $prev = $prev ? : 0;
        } else {
            $prev = 0;
        }

        $next_sql = "SELECT id FROM article WHERE id = ($aid + 1)";
        $next = $this->select($next_sql, false);
        $next = $next ? : 0;

        $article['prev'] = $prev;
        $article['next'] = $next;

        return $article;
    }

    /**
     * 找到所有的分类
     */
    function getCategory() {
        $sql = "SELECT * FROM category";

        return $this->select($sql);
    }

    /**
     * 找到所有的标签
     * TODO:出现的频率, 做成标签云
     */
    function getTags() {
        $sql = "SELECT * FROM tags";

        return $this->select($sql);
    }
}
